import { IDomEditor } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Button, message } from 'antd';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import './index.less';
import { WangEditorProps } from './types';
import { editorConfig, toolbarConfig } from './utils/config';
import { useWangEditor } from './utils/hooks';

/**
 * 富文本编辑器组件
 */
function WangEditor(props: WangEditorProps) {
  // editor 实例
  const editor = useRef<null | IDomEditor>(null);

  const { toggleEnable, destroyEditor } = useWangEditor(editor);

  // 编辑器内容
  const [html, setHtml] = useState(props.defaultHtml || '');
  const [text, setText] = useState('');

  useEffect(() => {
    if (editor.current !== null) {
      toggleEnable(props.readOnly || false);
    }
  }, [props.readOnly, editor]);

  useEffect(() => {
    // 及时销毁 editor ，重要！
    return () => {
      destroyEditor();
    };
  }, [editor]);

  useEffect(() => {
    setHtml(props.defaultHtml || '');
  }, [props.defaultHtml]);

  const saveWEInfo = useCallback(() => {
    const textData = editor.current?.getText().toString();
    if (!textData) return;
    if (!props.saveWEInfo) return;
    props.saveWEInfo(html.toString());
  }, [editor]);

  const onChangeInfo = (editor: IDomEditor) => {
    setHtml(editor.getHtml());
    setText(editor.getText().toString());
  };

  const onCreated = (_editor: IDomEditor) => (editor.current = _editor);

  return (
    <div id={props.editorId} className="rt-libs-wang-editor-box">
      <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <Toolbar
          editor={editor.current}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{
            borderBottom: '1px solid #ccc',
            display: props.readOnly ? 'none' : 'block',
          }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={onCreated}
          onChange={(editor) => onChangeInfo(editor)}
          mode="default"
          style={{ height: `${props.height || 500}px`, overflowY: 'hidden' }}
        />
      </div>
      {!props.readOnly && (
        <div className="rt-libs-save-box">
          {props.getText && (
            <CopyToClipboard
              text={text}
              onCopy={() => message.success('复制成功')}
            >
              <Button ghost type="primary" className="mx-1">
                提取文本
              </Button>
            </CopyToClipboard>
          )}
          <Button type="primary" className="mx-1" onClick={saveWEInfo}>
            保存
          </Button>
        </div>
      )}
    </div>
  );
}

export default WangEditor;
